<?php
define('TEMP_FILE', './Uploads/image');

/**
 * Created by PhpStorm.
 * User: 刘鹏
 * Date: 2017/7/5
 * Time: 11:20
 */
class MaterialAction extends Action {

    /**
     * 添加素材
     *
     * @param string $name          图文素材名
     * @param        $module        所属模块
     * @param string $xml           图文内容XML
     * @param        $public        0-公共素材库/1-我的素材库
     * @param string $type          news-图文/...
     * @param string $tags          标签
     * @param int    $deleted       0-未删除-一定是0
     * @param null   $groupId       分组id
     * @param null   $accessTag     访问标签
     * @param bool   $needReturn    是否需要向接口返回: false-不向接口返回, 向页面输出/true-需要
     */
    public function add($name = '', $module, $xml = '', $public='', $type = '', $tags = '', $deleted = 0, $groupId = NULL, $accessTag = NULL, $needReturn = FALSE)
    {
		$retVal = Session::init();
		if (!$retVal && !$needReturn) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $ModuleT = M("module_group");
        Session::switchCustomer($customerId);

        /** 新增,文章新增接口, jie */
        if ($type == 'content') {
            // 此时调用文章接口 TODO: 没有兼容修改$needReturn参数
            MiContentAction::saveNewContent(null, $public);
            return;
        }
        $materialId = $this->addData($name, $module, $xml, $public, $type, $groupId, $tags, $deleted, $accessTag, $needReturn);
		if (!$materialId) {
            if ($needReturn) {  // 需要调用: AdOrder接口调用
                $result = new stdClass();
                $result->id = -1;
                return $result;
            } else {    // 直接向页面返回
                return;
            }
		}

		// 返回添加的数据
        $result = new stdClass();
        $result->id = $materialId;
        $result->name = $name;
        $result->module = $module;
        $result->accessTag = $accessTag;
        $result->tags = $tags;
        $result->xml = nl2br($xml);
        $result->updateTime = date('Y-m-d H:i:s');
        $result->deleted = $deleted;

        $whereModule["modules"] = array('like', "%$module%");
        $moduleArr = $ModuleT->where($whereModule)->find();
        $result->iconurl = $moduleArr["iconurl"];
        $result->modulename = $moduleArr["name"];

        if ($needReturn) {  // 需要向接口调用返回
            return $result;
        }
		Output::instance()->object($result);

    }
    public static function downloadMedia1($imgUrl)
	{
        $ch = curl_init($imgUrl);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);

        $extension = '.jpg';
        $filename = md5 ( $imgUrl );
        $lp = LOCAL_PIC_PATH . '\\' . $filename . $extension;

        $fp = fopen($lp, 'w');
        if (!$fp) {
            fwrite($fp, $package);
            fclose($fp);
        } else {
            return;
        }
        return $lp;
    }

	/**
	 * xml转换后的数组
	 * @param $xml  要转换的xml
	 * @return mixed  返回的xml转换后的数组
	 */
    public function uploadXmlNewsToWeiXin($xml,$mediaId){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$ind_media_info=M('ind_media_info');
		Session::switchCustomer($customerId);
		$endImg=$ind_media_info->where("id=$mediaId")->field('needTailPic,TailPicUrl')->find();
		if($endImg['needTailPic']==1){
			$endPic=$endImg['TailPicUrl'];
			$img_preg = '/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i';
			$imgPic="<p><img src='".$endPic."' width='100%'/></p><p><br/></p>";
			preg_match_all($img_preg,$imgPic,$endPic_match);
			$endImg_result = self::saveFile($endPic_match[1][0], message_type_image);   //下载图片资源
			$endImg_msg=WeixinApi::uploadImage($endImg_result,$mediaId);
			@unlink($endImg_result['path']);//删除图片

			$endImg_msg=json_decode($endImg_msg,true);
			$imgPic=str_replace($endPic,$endImg_msg['url'],$imgPic);
		}else{
			$imgPic='';
		}

		$arr=json_decode(json_encode((array) simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA)), true);
		foreach($arr['Articles']['item'] as $key=>$value){
			if(!is_array($value)){
				foreach($arr['Articles'] as $key=>$value){
					unset($arr['Articles']);
					$arr['Articles']['item'][]=$value;
				}
			}
			break;
		}
		foreach($arr['Articles']['item'] as $key=>$value){
			$img_preg = '/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i';
			preg_match_all($img_preg,$value['content'],$img_match);
			if(!empty($img_match[0])){
				foreach($img_match[1] as $k=>$v){
					if(strpos($v,WxPic) !==false && strpos($v,WxPicParams) ===false )
					{
						$v.= WxPicParams;
					}
					$img_result = self::saveFile($v, message_type_image);   //下载图片资源
					$img_msg=WeixinApi::uploadImage($img_result,$mediaId);
					@unlink($img_result['path']);//删除图片
					$img_msg=json_decode($img_msg,true);
					$value['content']=str_replace($v,$img_msg['url'],$value['content']);
				}
			}
			$value['content']=$value['content'].$imgPic;
			foreach($value as $k=>$v){
				if(is_array($v)){
					$data[$key][$k]='';
				}else{
					$data[$key][$k]=$v;
				}
			}
		}
		return $data;
    }

    /**
     * 添加素材
     *
     * @param        $name
     * @param        $module        素材类别
     * @param        $xml           素材内容
     * @param        $public        0-公共素材/1-个人素材
     * @param string $groupId
     * @param string $type
     * @param string $tags
     * @param int    $deleted       0
     * @param null   $groupId
     * @param null   $accessTag     访问标签
     * @param bool   $needReturn
     *
     * @return mixed|void
     */
    public function addData($name, $module, $xml, $public, $type, $tags = '', $deleted = 0, $groupId = NULL, $accessTag = NULL, $needReturn = FALSE)
    {
		$customerId = Session::$user["customerId"];
		$userId = Session::$user["id"];

		// 初始化模型
		$Material = D("Material");
		$MaterialTags = D("MaterialTags");

		// 验证参数合法性,合法则删除
		$date = date('Y-m-d H:i:s');
		$Material->create();
		$Material->name = $name;
		$Material->module = $module;
		$Material->backups = 0;
		$Material->xml = $xml;
		$Material->accessTag = $accessTag;
        // ihziluoh 添加标签
        if (!empty($accessTag)) {
            addAccessTags($accessTag);
        }
		$Material->updateTime = $date;
		$Material->type = $type;
		$Material->deleted = $deleted;
		$Material->userId = $userId;
		$Material->public = $public;
		if ($groupId != NULL) {
			$Material->groupId = $groupId;
		}
		$materialId = $Material->add();
		$fullName = Session::$user["fullName"];
        R('Log/add', array('material', '145', '微信素材库', op_add, $Material->getLastSql(), $fullName . '添加素材'));

		if (!$materialId) { // 素材添加失败
		    if ($needReturn) {  // 需要向接口返回, 不向页面返回内容
		        return false;
            } else {    // 向页面返回错误
                Output::instance()->resultCode(code_sql_error);
                return;
            }
		}

		// 再插入到素材对应的标签表,先用,分割tag
		$tagarr = explode(',',$tags);
		foreach ($tagarr as $tag ) {
			// 插入到tag表中 TODO: 考虑多条一起加
			$data['materialId'] = $materialId;
			$data['tag'] = $tag;
			$MaterialTags->add($data);
		}

		return $materialId;
	}

    /* 获取素材列表
     * type: 指定素材类别
	 * tag: 指定素材标签，可选
	 * toBr: 替换回车为<br />标签
     */
    //http://localhost/Material.json/?module=text
    public function index($module='', $name='',$toBr = true, $deleted = null, $order="updateTime", $orderBy="desc", $start=0, $limit=25){
    	$retVal = Session::init();
 		if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}
		$cid = Session::$user["customerId"];
    	//$module,$tag=''
    	$Material = D("Material");
    	if ($module != '') {
    		$moduleArray = explode(",", $module);
    		$mapArr = array();
    		foreach ($moduleArray as $m) {
    			array_push($mapArr, array('eq', $m));
    		}
    		array_push($mapArr, "or");
    		$map["material.module"] = $mapArr;
    	}
    	if (isset($deleted)) {
    		$map["material.deleted"] = $deleted;
    	}
		if($name!='' && $name!=' ' ){
			$map["material.name"] = array('like','%'.$name.'%');
		}
    	$arr  = $Material->alias('material')
			->where($map)
			->join("wx_module_group ON wx_module_group.modules = CONCAT('%',material.module, '%')")
			->join("wx_mishare sta on material.id=sta.moduleId and sta.module='mall'")
			->field('material.*, wx_module_group.iconurl, wx_module_group.name as modulename,sta.viewUv as uv')
			->order("$order $orderBy")
			->group("material.id")
			->limit("$start,$limit")->select();
    	$MaterialTags = D("MaterialTags");
    	for ($i = 0; $i < count($arr); $i++) {
    		$tagsArr = $MaterialTags->where("materialId='". $arr[$i]['id'] . "'")->order("id asc")->select();

    		$tags = "";
    		foreach ($tagsArr as $tag) {
    			$tags = $tags . $tag['tag'] . ',';
    		}
    		if (count($tagsArr) > 0) {
    			$tags = substr($tags, 0, strlen($tags) - 1);
    			$arr[$i]['tags'] = $tags;
    		}

    		$arr[$i]['modulename'] = $arr[$i]['modulename'];

    		// replace html
    		if ($toBr && $arr[$i]['xml'] != '') {
    			$arr[$i]['xml'] = nl2br($arr[$i]['xml']);
    		}
    	}
		if($arr) {
			if (isset($deleted)) {
				$condition["deleted"] = $deleted;
			}
			if ($module == '') {
				Output::instance()->objArray($arr,$Material->where($condition)->count());
			} else {
				$condition['module']= $mapArr;
				$Material->where($condition)->count();

				Output::instance()->objArray($arr,$Material->where($condition)->count());
			}
		} else {
			Output::instance()->resultCode(code_success,"未找到素材");
		}

    }

    public function getMaterialByModule($module){
    	$retVal = Session::init();
    	if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}

    	//$module,$tag=''
    	$Material = D("Material");
    	$condition['module'] = array('eq',$module);
    	$condition['deleted'] = array('eq',0);

    	$result = $Material->where($condition)->find();

    	if($result){
    		Output::instance()->object($result);
    	}else{
    		Output::instance()->resultCode(code_custom_error,"没有数据");
    	}
    }


    public function getMaterialByGroupId($module,$groupId){
    	$retVal = Session::init();
    	if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}

    	//$module,$tag=''
    	$Material = D("Material");
    	$condition['groupId'] = array('eq',$groupId);
    	$condition['module'] = array('eq',$module);
    	$condition['deleted'] = array('eq',0);

    	$result = $Material->where($condition)->find();

    	if($result){
	    	Output::instance()->object($result);
    	}else{
    		Output::instance()->resultCode(code_custom_error,"没有数据");
    	}
    }


    /* 删除指定ID的素材
     * mid: 素材id
     * http://localhost/Material/delete.json/mid/5
     */
    public function delete($mid){
    	$retVal = Session::init();
 		if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}

    	// 初始化模型
    	$Material     = D("Material");
    	$MaterialTags = D("MaterialTags");
    	$media_id = $MaterialTags->where("materialId=$mid")->getField("media_id");
		if($media_id){
			WeixinApi::del_material($media_id);
		}
		// 验证参数合法性,合法则删除
		$result = $MaterialTags->where("materialId=$mid")->delete();
		if(!$result){
			//Output::instance()->resultCode(code_custom_error,"没有需要删除的数据");
			//return;
		}

		//$result = $Material->where("id=$mid")->delete();
		$condition['id'] = array('eq',$mid);
		$mat = $Material->where($condition)->find();

		$Material->deleted = 1;
		$result = $Material->save();
// 		Log::write('material delete sql is:'.$Material->getLastSql());
		if(!$result){
			Output::instance()->resultCode(code_custom_error,"没有需要删除的数据");
			return;
		}

    	Output::instance()->resultCode(code_success);
    	R('Log/add', array($mat["module"], $mid, op_delete, $mat["name"]));
    }

    /* myq 修改指定ID的素材   joymap添加图文
     * mid: 素材id
    * http://localhost/Material/update.json/mid/4/name/testname4/module/testmodule/tags/abc1,bcd/xml/testxml
 	*/
    public function update($mid, $name,$module,$xml,$tags='',$deleted = 0,$accessTag=NULL,$public=''){

    	$ModuleT = M("module_group");

    	$retVal = Session::init();
 		if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}

    	$result = $this->updateData($mid, $name,$module,$xml,$tags,$deleted,$accessTag,$public);
		if (!$result) {
			return;
		}
		// 返回更新的数据
		$result = new stdClass();
		$result->id = $mid;
		$result->name = $name;
		$result->module = $module;
		$result->tags = $tags;
		$result->accessTag = $accessTag;
		$result->xml = nl2br($xml);
		$result->updateTime = $date;

		$whereModule["modules"] = array('like',"%$module%");
		$moduleArr = $ModuleT->where($whereModule)->find();
		$result->iconurl = $moduleArr["iconurl"];
		$result->modulename = $moduleArr["name"];
		Output::instance()->object($result);

		R('Log/add', array($module, $mid, op_update, $name));
    }


    public function updateData($mid, $name,$module='',$xml='',$tags='',$deleted = 0,$accessTag=NULL,$public, $mediaId = 0){

        $customerId = Session::$user['customerId'];
        Session::switchCustomer($customerId);
        // 初始化模型
    	$Material = M("Material");
    	$MaterialTags = D("MaterialTags");

    	 if($module=='') {
			 $data['name']=$name;
			 $result=$Material->save($data);
			 if ($result) {
				 Output::instance()->resultCode(code_success);
			 } else {
				 Output::instance()->resultCode(code_sql_error);
			 }
		 }

    	//先更新素材表
		if($module==message_type_image){
			$materialInfo = $Material->where("id=$mid")->find();
			if($materialInfo['xml']!=$xml&&$materialInfo['media_id']){
				WeixinApi::del_material($materialInfo['media_id'], $mediaId);
				$Material->where("id=$mid")->setField("media_id",null);
			}
		}

    	$date = date('Y-m-d H:i:s');
    	$Material->find($mid);
		$data['name']=$name;
		$data['module']=$module;
		$data['xml']=$xml;
		$data['accessTag']=$accessTag;
		$data['updateTime']=$date;
		$data['type']=$module;
		$data['deleted']=$deleted;
		$data['name']=$name;
    	$result = $Material->where("id=$mid")->save($data);
    	if ($result == false) {
    		Output::instance()->resultCode(code_sql_error);
    		return;
    	}

		/*清除redis中的缓存*/
		self::cacheDel($mid, $customerId);

		if($module=='material'){
//			$module_mass_havesend=M('module_mass_havesend');
//			$data['status']=4;
//			$module_mass_havesend->where("materialId=$mid")->save($data);
			$material_group_list=M('material_group_list');
			$material_group_list->where("materialId=$mid")->delete();
			$userId=$public==0?$public:Session::$user['id'];
			$tags=explode(',',$tags);
			if(!empty($tags)){
				for($i=0;$i<count($tags);$i++){
					$arr[$i]['materialId']=$mid;
					$arr[$i]['groupId']=$tags[$i];
					$arr[$i]['userId']=$userId;
				}
				$result=$material_group_list->addAll($arr);
				if (!$result) {
					Output::instance()->resultCode(code_sql_error);
					return;
				}else{
					Output::instance()->resultCode(code_success);
					return;

				}
			}
		}



    	// 再删除以前对应的标签
    	$MaterialTags->where("materialid=$mid")->delete();

    	// 再插入到素材对应的标签表,先用,分割tag
    	$tagarr = explode(',',$tags);
    	foreach ($tagarr as $tag ) {
    		// 插入到tag表中
    		$MaterialTags->create();
    		$MaterialTags->materialId = $mid;
    		$MaterialTags->tag = $tag;
    		$MaterialTags->add();
    	}

    	R('Log/add', array($module, $mid, op_update, $name));

    	return true;
    }


    private function getKeyword($id) {
    	$cid = Session::$user["customerId"];

    	if($cid == 0){
    		$prefix = C('ORIGINAL_DB_PREFIX');
    	}else{
    		$prefix = C('ORIGINAL_DB_PREFIX').$cid.'_';
    	}
    	//$module,$tag=''
    	$MaterialKeyword = new Model();
    	$sql = 'select k.*,material.module from '
    	.$prefix.'material_keyword as k ,'
    	.$prefix.'material as material '
    	.' where k.materialId in ('.$id.')'
    	.' and k.materialId = material.id'
    	.' and k.deleted = 0';
    	$countSql = 'select count(*) as tp_count from '.$prefix.'material_keyword where materialId in ('.id.') LIMIT 1 ';
    	$count = $MaterialKeyword->query($countSql);
    	$arr = $MaterialKeyword->query($sql);
    	//     		Log::write('get materialKeyword sql is:'.$MaterialKeyword->getLastSql());
    	return $arr;
    }

    public function getMaterialKeyword($id){
    	$retVal = Session::init();
    	if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}

    	$arr = $this->getKeyword($id);
    	if($arr) {
    		Output::instance()->objArray($arr);
    	} else {
    		Output::instance()->resultCode(code_success,"未找到素材关键字");
    	}
    }


    public function getMultiMaterialKeyword($ids) {
    	$retVal = Session::init();
    	if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}

    	$idArray = explode(",", $ids);
    	$arr = array();
    	foreach ($idArray as $id) {
    		$keywordArr = $this->getKeyword($id);
    		if ($keywordArr) {
    			array_push($arr, $keywordArr);
    		}
    	}

    	Output::instance()->objArray($arr);
    }

    /**
     * 获取互动消息的具体信息
     *
     * @param      $id
     * @param bool $toBr
     */
    public function getMaterialById($id, $toBr = true, $module = '', $needReturn = FALSE)
    {
    	$retVal = Session::init();
    	if (!$retVal) {
    	    if ($needReturn) {
    	        return ['code' => code_access_denied, 'msg' => '未登录'];
            }
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}

        $customerId = Session::$user["customerId"];
    	Session::switchCustomer(0);
        $Model_MMCS = M('media_mass_config_schedule');
        Session::switchCustomer($customerId);
    	$MaterialModel = D("Material");

    	$result = $MaterialModel->where(['id' => $id])->find();

        if (!$result) {
            if ($needReturn) {
                return ['code' => code_custom_error, 'msg' => '未找到素材'];
            }
            Output::instance()->resultCode(code_custom_error, "未找到素材");
            return;
        }

        if ($module == 'material') {
            $material_grou_list = M('material_group_list as a');
            $arr = $material_grou_list
                ->where(['materialId' => $id])
                ->join("wx_" . $customerId . "_material_group as b on a.groupid = b.id")
                ->getField('groupId, groupName');

            $scheduleInfo = $Model_MMCS
                ->alias('mmcs')
                ->join('wx_customer_weixin_profile cwp ON cwp.mediaId = mmcs.mediaId')
                ->join('wx_' . $customerId . '_mass_review mr ON mr.materialId = mmcs.materialId AND mr.mediaId = mmcs.mediaId')
                ->where(['mmcs.materialId' => $id])
                ->field('mmcs.id as scheduleId, mmcs.scheduleTime, mmcs.sendTime, mmcs.reviewType,
                        cwp.mediaId, cwp.nick_name as mediaName,
                        mr.createTime as reviewTime, mr.reviewOpinion')
                ->order('mmcs.id desc')
                ->find();

            if (empty($arr)) {
                $result['groupId'] = '';
                $result['groupName'] = '';
            } else {
                $groupIds = '';
                $groupNames = '';

                foreach ($arr as $k => $v) {
                    $groupIds .= ',' . $k;
                    $groupNames .= ',' . $v;
                }

                $groupIds = substr("$groupIds", 1);
                $groupNames = substr("$groupNames", 1);
                $result['groupId'] = $groupIds;
                $result['groupName'] = $groupNames;
            }

            $result['scheduleId'] = empty($scheduleInfo['scheduleId']) ? 0 : $scheduleInfo['scheduleId'];
            $result['scheduleTime'] = empty($scheduleInfo['scheduleTime']) ? '' : $scheduleInfo['scheduleTime'];
            $result['sendTime'] = empty($scheduleInfo['sendTime']) ? '' : $scheduleInfo['sendTime'];
            $result['reviewType'] = $scheduleInfo['reviewType'];
            $result['mediaId'] = empty($scheduleInfo['mediaId']) ? 0 : $scheduleInfo['mediaId'];
            $result['mediaName'] = empty($scheduleInfo['mediaName']) ? '' : $scheduleInfo['mediaName'];
            $result['reviewTime'] = empty($scheduleInfo['reviewTime']) ? '' : $scheduleInfo['reviewTime'];
            $result['reviewOpinion'] = empty($scheduleInfo['reviewOpinion']) ? '' : $scheduleInfo['reviewOpinion'];
		}
    	if ($toBr && $result['xml'] != '') {
    		$result['xml'] = nl2br($result['xml']);
    	}

        if ($needReturn) {
            return $result;
        }
    	Output::instance()->object($result);
    }

    /**
     * 获取素材列表
     *
     * @param string $kw        关键字筛选
     * @param string $module    指定素材类别
     * @param bool   $toBr      替换回车为<br />标签:T/F
     * @param int    $deleted   ->0
     * @param string $order
     * @param string $orderBy
     * @param int    $start
     * @param int    $limit
     */
    public function getMaterialAndKeyword($kw='',$module='', $toBr = true, $deleted = 0, $order="updateTime", $orderBy="desc", $start=0, $limit=25){
    	$retVal = Session::init();
    	if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}
    	$cid = Session::$user["customerId"];
    	$Material = D("Material");

    	if ($module != '') {
    		$moduleArray = explode(",", $module);
    		$mapArr = array();
    		foreach ($moduleArray as $m) {
    			array_push($mapArr, array('eq', $m));
    		}
    		array_push($mapArr, "or");
    		$map["material.module"] = $mapArr;
    	}
    	if (isset($deleted)) {
    		$map["material.deleted"] = 0; // $deleted;
    	}
    	if (!empty($kw)) {
     		$map["kd.keyword"] = array('like','%'.trim($kw).'%');
    	}

    	$arr  = $Material->alias('material')
    			->where($map)
    			->join("wx_module_group ON wx_module_group.modules LIKE CONCAT('%',material.module, '%')")
    			->join("wx_".$cid."_material_keyword as kd on kd.materialId = material.id and kd.deleted <>1 ")
    			->field("material.*, wx_module_group.iconurl,
    					wx_module_group.name as modulename,
    					kd.id as kid,
    					GROUP_CONCAT(kd.ruleName) as ruleNames,
    					GROUP_CONCAT(kd.keyword) as keywords ,
    					GROUP_CONCAT(kd.exactMatch) as exactMatchs
    					")
    			->group("material.id")
    			->order("$order $orderBy")
    			->limit("$start,$limit")->select();

    	if($toBr){
	    	for ($i = 0; $i < count($arr); $i++) {
					$arr[$i]['keywords'] = implode(array_unique(explode(',', $arr[$i]['keywords'])));
	    		// replace html
	    		if ($arr[$i]['xml'] != '') {
	    			$arr[$i]['xml'] = nl2br($arr[$i]['xml']);
	    		}
	    	}
    	}
    	$count = $Material->alias('material')
            ->where($map)
            ->join("wx_module_group ON wx_module_group.modules LIKE CONCAT('%',material.module, '%')")
            ->join("wx_".$cid."_material_keyword as kd on kd.materialId = material.id and kd.deleted <>1 ")
            ->group("material.id")
            ->order("$order $orderBy")
    	->count();

    	if($arr) {
    		Output::instance()->objArray($arr,$count);
    	} else {
    		Output::instance()->resultCode(code_success);
    	}

    }

    public function getMaterialListByModule($module){
    	$retVal = Session::init();
    	if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}

    	//$module,$tag=''
    	$Material = M("material");
    	$condition['module'] = array('eq',$module);
    	$condition['deleted'] = array('eq',0);
    	$result = $Material->where($condition)->select();
    	if($result){
    		Output::instance()->objArray($result);
    	}else{
    		Output::instance()->resultCode(code_success);
    	}
    }

	/**
	 * 删除素材
	 * 描述：用户删除自己的素材组，只有微信素材库员才可以删除素材库的组
	 * $materialId：素材id
	 * $groupId：素材id（如果传组id则删除素材组里的这个素材，不传则删除用户下所有组的的这个素材）
	 */
	public function deleteMaterial($materialId, $type=''){
		//判断是否为非法登录
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/*新增,文章删除接口,jie */
		if($type == 'content'){
			//此时调用文章接口
			MiContentAction::delNewContent($materialId);
			return;
		}

		$customerId = Session::$user["customerId"];
		$fullName = Session::$user["fullName"];
        Session::switchCustomer(0);
        $Model_MMCS = M('media_mass_config_schedule');
        Session::switchCustomer($customerId);
		//实例化开发平台数据模型
		$material_group=M('material_group_list');
		$material=M('material');
        
        // 删除素材排期数据
        $Model_MMCS->where(['materialId' => $materialId])->save(['materialId' => null]);
        
		//删除该用户每个分组下的这条数据
		$where['id']=array('in',$materialId);
		$result_group=$material_group->where("materialId in ($materialId)")->delete();
		$result=$material->where($where)->delete();
		R('Log/add',array('material','145','微信素材库',op_delete,$material->getLastSql(),$fullName.'删除素材'));
		//判断是否成功
		if ($result) {
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->object(array(
				'code' => -1,
				'msg' => '删除失败',
				'data' => '',
			));
			return;
		}
	}
	/**
	 * 获取素材分组
	 * 描述：获取分组，每个类型下的分组是不同！
	 * $public：识别是素材库还是个人素材（0:素材库/1:个人素材）
	 * $type：素材的类型
	 */
	public function materialGroupList($public,$type){
		//判断是否为非法登录
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$userId = $public==0?0:Session::$user["customerId"];
		$fullName=Session::$user["fullName"];
		//实例化开发平台数据模型
		$material_group=M('material_group');
		$material_group_list=M('material_group_list');
		$material=M('material');
		//拼接查询条件
		$where['groupType']=array('eq',$type);
		$where['userId']=array('eq',$userId);
		$where['deleted']=array('eq',0);

		$all_conut['type']=array('eq',$type);
		$all_conut['public']=array('eq',$public);
		//查询该用户下所有素材组
		$arr=$material_group->where($where)->field("id,groupName")->select();
		//判断该用户下是否有素材组
		if(empty($arr)){
			//查询所有素材

			$count=$material->where($all_conut)->count();
			$arr[0]['id']='';
			$arr[0]['groupName']='全部素材';
			$arr[0]['count']=$count;
			Output::instance()->objArray($arr);
			return;
		}
		//查询每个素材组有多少个素材（包括不属于他的组）
		$arr_conut=$material_group_list->where("userId=$userId")->group('groupId')->getField("groupId,count('groupId') as num");
		//素材组素材数量进行处理
		foreach($arr as $k=>$v) {
			if(isset($arr_conut[$v['id']])) {
				$arr[$k]['count']=$arr_conut[$v['id']];
			}else{
				$arr[$k]['count']=0;
			}
		}
		//所有素材的数量
		$count=$material->where($all_conut)->count();
		$arr[$k+1]['id']='';
		$arr[$k+1]['groupName']='全部素材';
		$arr[$k+1]['count']=$count;
		$arr=array_reverse($arr);
//		R('Log/add',array('material','145','微信素材库',op_find,$material_group->getLastSql(),$fullName.'查看'.$public==0?'素材库':'我的素材的'.$type.'的素材分组'));
		if($arr) {
			Output::instance()->objArray($arr);

		} else {
			Output::instance()->object(array(
				'code' => -1,
				'msg' => '获取素材分组失败',
				'data' => '',
			));
			return;
		}
	}
	/**
	 * 添加素材分组接口
	 * 描述：用户可以给自己添加素材组，素材库的组只能素材库管理员添加
	 * $userId：素材组的创建者id
	 * $groupType：素材组的类型
	 * $groupName：素材组的名称
	 * $description：素材的描述
	 */
	public function materialGroupAdd($public,$groupType,$groupName,$description='',$materialId=''){
		//判断是否为非法登录
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		//取session的平台id
		$customerId = Session::$user["customerId"];
		$fullName = Session::$user["fullName"];
		$userId= $public== 0 ? 0 : Session::$user["customerId"];
		//实例化开发平台数据模型
		$material_group=M('material_group');
		//素材组要入库的信息
		$data['groupType']=$groupType;
		$data['groupName']=$groupName;
		$data['fromCustomerId']=$customerId;
		$data['userId']=$userId;
		$data['description']=$description;
		$data['deleted']=0;
		$data['createTime']=date("Y-m-d H:i:s");
		//入库
		$groupId=$material_group->add($data);
		if(!$groupId){
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		if($materialId){
			$material_group_list=M('material_group_list');
			$arr['userId']=$userId;
			$arr['materialId']=$materialId;
			$arr['groupId']=$groupId;
			$result=$material_group_list->add($arr);
		}

		R('Log/add',array('material','145','微信素材库',op_add,$material_group->getLastSql(),$fullName.'添加了'.$groupName.'分组'));
		//判断是否入库成功
		if ($result) {
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}

	}

    /**
     * 素材列表
     * 描述：根据不同的条件获取不同的素材
     *
     * @param int    $public    判断获取到是素材库的数据还是个人素材的数据
     * @param string $module    查询的哪个模块下的: 默认只有material, 如果要加上订单, 如要传使用','分割的字符串, 加上'AdOrder', 如: 'material,AdOrder'
     * @param string $type      获取素材的类型
     * @param string $groupId   获取素材组的数据
     * @param string $search    获取素材的关键字
     * @param int    $start     开始条数
     * @param int    $limit     每页显示多少条
     */
    public function materialList($public = 0, $module = 'material', $type = 'news', $groupId = '', $search = '', $start = 0, $limit = 20)
	{
		/** 判断登录 */
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/** 新增,适应文章列表接口,jie */
        if ($type == 'content') {
			// 此时调用文章接口
			MiContentAction::getNewContentList($search, $groupId, $public, $start, $limit);
			return;
		}
//        $start = ($start - 1) * $limit;
        $userId = ($public == 0) ? 0 : Session::$user["id"];
		$customerId = Session::$user["customerId"];

        // 实例化开发平台数据模型
        $material_group_list = M('material_group_list as a');
        // 实例化开发平台数据模型
        $material = M('material as a');

        // 查询是否有标题查询
		if(!empty($search)) {
			$where['name']= array("like","%".trim($search)."%");
		}
		if (count($arr_module = explode(',', $module) ) > 1) {
            $where['module'] = array('IN', $arr_module);
        } else {
            $where['module'] = array('eq', $module);
        }
        $where['backups'] = array('eq', 0);

        if (empty($groupId) && $userId != 0) {  // 此次查询是我的素材type类型的所有数据
            $where['type'] = array("eq", $type);
            $where['userId'] = array("eq", $userId);
            $where['public'] = array("eq", 1);
            $arr = $material
                ->where($where)
                ->join("wx_customer_user as b on a.userId=b.id")
                ->join('wx_customer_weixin_profile cwp on cwp.mediaId = a.mediaId')
                ->limit($start, $limit)
                ->field('a.*,b.fullName, cwp.nick_name as mediaName')
                ->order('id desc')
                ->select();
        } elseif (empty($groupId) && $userId == 0) {    // 此次查询是素材库type类型的所有数据
            $where['type'] = array("eq", $type);
            $where['public'] = array("eq", 0);
            $arr = $material
                ->where($where)
                ->join("wx_customer_user as b on a.userId=b.id")
                ->join('wx_customer_weixin_profile cwp on cwp.mediaId = a.mediaId')
                ->limit($start, $limit)
                ->field('a.*,b.fullName, cwp.nick_name as mediaName')
                ->order('id desc')
                ->select();
        } else {    // 此次查询的是素材组的数据
            $where['a.groupId'] = array('eq', $groupId);
            $arr = $material_group_list
                ->where($where)
                ->join("wx_" . $customerId . "_material as b on a.materialId=b.id")
                ->join("wx_customer_user as b on a.userId=b.id")
                ->join('wx_customer_weixin_profile cwp on cwp.mediaId = b.mediaId')
                ->limit($start, $limit)
                ->field('a.*,b.fullName, cwp.nick_name as mediaName')
                ->order('id desc')
                ->select();
        }

        if ($type == 'news') {
            $module_mass_havesend = M('module_mass_havesend');
            $mass_where['status'] = array('eq', 0);
            $mass_where['type'] = array('eq', 'news');
            $materialIds = $module_mass_havesend->where($mass_where)->getField('materialId', true);
            if (!empty($materialIds)) {
                // 如果有群发的进行加锁状态
                foreach ($arr as $k => $v) {
                    if (in_array($v['id'], $materialIds)) {
                        $arr[$k]['lock'] = 1;
                    } else {
                        $arr[$k]['lock'] = 0;
                    }
                }
            }
        }

		// 在没有数据的情况下
        if (empty($arr)) {
            Output::instance()->object(array(
                'code' => 1,
                'msg' => '没有任何素材'
            ));
            return;
        }
        if ($arr) {
            Output::instance()->objArray($arr);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }

	}

	/**
	 * 同步到我的素材/上传到素材库
	 * 描述：可以把我的素材上传到素材库，也可以把素材库的素材同步到我的素材
	 * $public：判断同步到是素材库的数据还是个人素材的数据
	 * $ids：素材的id（多个素材以逗号隔开）
	 */
	public function uploadMaterial($public,$ids, $type=''){
		// 断是否为非法登录
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/*新增,文章上传到素材库以及同步到我的素材库接口,jie*/
		if($type == 'content'){
			//此时调用文章接口
			MiContentAction::editMaterialLibrary($ids, $public);
			return;
		}

		//取session的平台id
		$fullName = Session::$user["fullName"];
		//实例化开发平台数据模型
		$material=M('material');
		//拼接查询条件
		$where['id']=array('in',$ids);
		$where['public']=array('eq',$public);
		//查询出要 同步到我的素材 或 上传到素材库 的素材
		$arr=$material->where($where)->select();
		$public=$public==0?1:0;
		$userId=Session::$user["id"];
		foreach($arr as $key=>$value) {
			$materialName=','.$value['name'];
			$arr[$key]['public']=$public;
			$arr[$key]['userId']=$userId;
			unset($arr[$key]['id']);
		}
		$materialName=substr("$materialName",1);
		//入库
		$result=$material->addAll($arr);
//		R('Log/add',array('material','145','微信素材库',op_find,$material->getLastSql(),$fullName.'把'.$materialName.'同步到'.$public==0?'我的素材':'素材库'));
		if($result) {
			Output::instance()->resultCode(code_success);
		}else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	/**
	 * 给素材打标签
	 * 描述：给素材打上多个标签
	 * $groupId： 组id
	 * $ids：素材的id（多个素材以逗号隔开）
	 */
	public function materialLableAdd($public,$materialIds='',$groupIds='')
	{
		// 断是否为非法登录
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		if(empty($materialIds)){
			Output::instance()->object(array(
				'code'=>-1,
				'msg'=>'没有选中的数据',
				'data'=>''
			));
			return;
		}
		//分割传过来的素材id
		$ids=explode(',',$materialIds);

		//取用户id
		$userId = $public==0?$public:Session::$user["id"];
		//实例化开发平台数据模型
		$material_group_list=D('material_group_list');
		if(count($ids)==1){
			$result=$material_group_list->where("materialId=$materialIds")->delete();
			if(empty($groupIds)){
				Output::instance()->object(array(
					'code'=>-2,
					'msg'=>'没有选中的素材分组',
					'data'=>''
				));
				return;
			}
			//分割传过来的素材组id
			$groupIds=explode(',',$groupIds);
			foreach($groupIds as $val){
				$arr[]=array('userId'=>$userId,'materialId'=>$materialIds,'groupId'=>$val);
			}
			$result=$material_group_list->addAll($arr);
		}else{
			if(empty($groupIds)){
				Output::instance()->object(array(
					'code'=>-2,
					'msg'=>'没有选中的素材分组',
					'data'=>''
				));
				return;
			}
			//分割传过来的素材组id
			$groupIds=explode(',',$groupIds);

			$materialGroupId=$material_group_list
				->where("materialId in ($materialIds)")
				->field('materialId,GROUP_CONCAT(groupId) as groupId')
				->group('materialId')
				->select();
			foreach ($materialGroupId as $key=>$value) {
				$groupIdArr=explode(',',$value['groupId']);
				$diff=array_diff($groupIds,$groupIdArr);
				foreach($diff as $val){
					$arr[]=array('userId'=>$userId,'materialId'=>$value['materialId'],'groupId'=>$val);
				}
			}
			//入库
			$result=$material_group_list->addAll($arr);
		}
//		R('Log/add',array('material','145','微信素材库',op_add,$material_group_list->getLastSql(),'给一个或多个素材打标签'));

		if($result) {
			Output::instance()->resultCode(code_success);
		}else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

    /**
     * 修改素材
     * 描述：可以把素材组的素材移动到其他素材组
     *
     * @param        $id            素材的id
     * @param string $name          要修改素材名称
     * @param string $xml           xml
     * @param string $type
     * @param bool   $needReturn
     * @param int    $mediaId       排期与素材绑定, 自媒体id
     * @param string $scheduleTime  排期与素材绑定, 排期日期
     * @return bool|void
     */
	public function saveMaterial($id,$name='',$xml='',$type='', $needReturn = FALSE, $mediaId = 0, $scheduleTime = '')
	{
		$retVal = Session::init();
		if (!$retVal && !$needReturn) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

        $customerId = Session::$user['customerId'];
        $userId     = Session::$user['id'];
        Session::switchCustomer(0);
        $Model_MMCS = M('media_mass_config_schedule');
        Session::switchCustomer($customerId);

		$fullName = Session::$user["fullName"];
		if(!empty($name)){
			$data['name']=$name;
		}
		if (!empty($xml)) {
			$downLoadDir = TEMP_FILE;//临时目录
			$newxml = '<xml><Articles>';
			$arr = json_decode(json_encode((array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
			foreach ($arr['Articles']['item'] as $key => $value) {
				if (!is_array($value)) {
					foreach ($arr['Articles'] as $key => $value) {
						unset($arr['Articles']);
						$arr['Articles']['item'][] = $value;
					}
				}
				break;
			}
			foreach ($arr['Articles']['item'] as $key => $value) {
				$img_preg = '/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i';
				preg_match_all($img_preg, $value['content'], $img_match);
				$content = $value['content'];
				if (!empty($img_match[0])) {
					foreach ($img_match[1] as $k => $v) {
						if ((strpos($v, WxPic) == false)) {
							continue;
						}
						$img = file_get_contents($v);
						if ($img == false) {
							continue;
						}
						if (!empty($img)) {
							//保存图片到服务器
							$fileimgname = time() . "-" . rand(1000, 9999) . '.jpeg';
							$filecachs = $downLoadDir . "/" . $fileimgname;
							//先保存在本地
							$int = file_put_contents($filecachs, $img);
							if (!$int) {
								continue;
							}
							//上传oss,获取链接
							$upRet = R('Upload/uploadLocalFileToOss', [$fileimgname, $filecachs]);
							$fileInfo = $upRet->path;
							if (!$fileInfo) {
								continue;
							}
							//替换文章中的路径
							$content = str_replace($v, $fileInfo, $content);
                          	$content = str_replace('&tp=webp&wxfrom=5&wx_lazy=1', '', $content);
						}
					}
				}
				is_array($value['title']) ? $value['title'] = '': '';
				is_array($value['picUrl']) ? $value['picUrl'] = '': '';
				is_array($value['author']) ? $value['author'] = '': '';
				is_array($value['digest']) ? $value['digest'] = '': '';
				is_array($value['url']) ? $value['url'] = '': '';
              	is_array($content) ? $content = '': '';
				$newxml .= '<item><title><![CDATA[' . $value['title'] . ']]></title><content><![CDATA[' .$content . ']]></content><picUrl><![CDATA[' . $value['picUrl'] . ']]></picUrl><author><![CDATA[' . $value['author'] . ']]></author><description><![CDATA[' . $value['digest'] . ']]></description><content_source_url><![CDATA[' . $value['url'] . ']]></content_source_url></item>';
			}
			$newxml .= '</Articles></xml>';
			$data['xml'] = $newxml;
		}
		$data['updateTime'] = date('Y-m-d H:i:s');
		$where['id']=array('eq',$id);
		$Material = D("Material");
		$result=$Material->where($where)->save($data);

        /** 素材内容与排期关联 */
        if ($mediaId > 0) { // 选择了自媒体
            // 选择了自媒体, 要求必选日期
            if (empty($scheduleTime)) { // 排期日期为空
                if (is_numeric($result)) {
                    $Out = ['code' => -1, 'msg' => '缺少参数-排期日期', 'data' => []];
                } else {
                    $Out = ['code' => -1, 'msg' => '缺少参数-排期日期, 且素材内容添加错误', 'data' => []];
                }

                if (!$needReturn) {
                    Output::instance()->object($Out);
                    return;
                }
            }

            // 查询系统排期
            $scheduleId = $Model_MMCS->where(['mediaId' => $mediaId, 'scheduleTime' => $scheduleTime])->getField('id');
            if (!$scheduleId) { // 如果排期id不存在, 需要创建一个排期
                // 创建一个排期id
                $rateCardInfo = R('MassSchedules/bespeakAd', [0, '', json_encode( [$mediaId] ), $scheduleTime, 0, 1, TRUE]);
                $conf = $rateCardInfo['results'][0]['scheduleConfig'];
                $sendTime = $rateCardInfo['results'][0]['sendTime'];
                $schedule = R('MassSchedules/setSchedulesStatus', [ 0, $mediaId, null, $scheduleTime, $sendTime, $conf, TRUE]);

                if ($schedule['code'] == 0) {
                    $scheduleId = $schedule['scheduleId'];
                } else {
                    $Out = ['code' => -1, 'msg' => '创建该日默认排期错误', 'data' => []];
                    if (!$needReturn) {
                        Output::instance()->object($Out);
                        return;
                    }
                }
            }

            $rateCardInfo = R('MassSchedules/saveMateriaSchedules', [$scheduleId, $id]);    // 这个方法里做了数据向页面输出了
            // 20171214 - 修改素材内容与排期绑定, 由于这个绑定的方法中有返回, 所以截断下方的数据返回
            return;
        }

        if ($needReturn) {
            return $result;
        }

		R('Log/add',array('material','145','微信素材库',op_update,$Material->getLastSql(),$fullName.'修改了素材'.$name));

		if($result) {
				Output::instance()->object(array(
					'code' => 1,
					'msg' => '修改成功',
					'data' => '',
				));
				return;
			}else {
				Output::instance()->object(array(
					'code' => -1,
					'msg' => '修改失败',
					'data' => '',
				));
				return;
			}
	}
	/**
	 * 删除组
	 *描述：删除素材组
	 * $groupId：素材组id
	 */
	public function materialGroupDelete($groupId){
		//判断非法登录
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$groupId=intval($groupId);
		$fullName = Session::$user["fullName"];

		//删除条件
		$where['id']=array('eq',$groupId);
		$material_group=M('material_group');
		$material_group_list=M('material_group_list');
		$result=$material_group->where($where)->delete();
		$groupName=$material_group->where($where)->getField('groupName',true);
		$result_group=$material_group_list->where("groupId=$groupId")->delete();
		R('Log/add',array('material','145','微信素材库',op_delete,$material_group->getLastSql(),$fullName.'删除素材组'.$groupName[0]));
		if($result) {
			Output::instance()->resultCode(code_success);
		}else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	/**
	 * 素材解锁
	 * @param $materialId  要解锁的id
	 */
	public function unlockMaterial($materialId){
		//判断非法登录
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$Material = D("Material");
		$data['lockStatus']=0;
		$data['lockTime']=date("Y-m-d H:i:s");
		$where['id']=array('eq',$materialId);
		$result=$Material->where($where)->save($data);
		if($result){
			$module_mass_havesend=M('module_mass_havesend');
			$mass_where['materialId']=array('eq',$materialId);
			$mass_where['status']=array('eq',0);
			$save['status']=4;
			$result_mass=$module_mass_havesend->where($mass_where)->save($save);
			if($result_mass){
				$return['code']=1;
				$return['msg']='解锁成功';
				Output::instance()->objArray($return);
			}else{
				$return['code']=2;
				$return['msg']='解锁失败';
				Output::instance()->objArray($return);
			}
		}

	}
	/**
	 * 下载资源到本地
	 * 描述：通过oss地址，把资源下载到本地
	 * $path：图片下载到本地地址
	 * $type：下载的资源类型
	 */
	public function saveFile($path,$type) {
		$fileName = pathinfo($path);
		$image_name =ABSPATH .strToLower($fileName['basename']);
		$ch = curl_init ($path);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
		$img = curl_exec ($ch);
		curl_close ($ch);
		$fp = fopen($image_name,'w');
		fwrite($fp, $img);
		fclose($fp);
		//如果图片过大，进行图片压缩
		if($type=='image'&&filesize($image_name)>=2048000){
			self::resizejpg($image_name,2000,$image_name);
		}
		$result['size'] = filesize($image_name);
		$result['path']=$image_name;
		$result['content-type']=$type."/".$fileName['extension'];
		return $result;
	}
	/**
	 * 图片压缩
	 * $imgsrc：图片l路径
	 * $undersize：图片压缩的大小
	 * $savepath：压缩后的路径
	 */
	function resizejpg($imgsrc,$undersize,$savepath)
	{						//输出格式
		$arr = getimagesize($imgsrc);    						//获取源文件的长宽信息
		$size = filesize($imgsrc);
		$size = ceil($size/1024);       						//计算源文件的大小(kb)
		$percentum = $undersize / $size; 						//变成原来的多少
		if($size <= $undersize){								//已经满足的照片则不予处理
			return ;
		}
		$dest_area = $arr[0]*$arr[1]*$percentum;          		//转换之后的面积
		$newpercent = sqrt($dest_area/($arr[0]*$arr[1])); 		//长宽变化的比率
		$imgWidth = $arr[0]*$newpercent; 			       		//计算出来的宽缩放后的宽度
		$imgHeight = $arr[1]*$newpercent; 				  		//计算出来的高缩放后的高度

		// Create image and define colors
		$imgsrc = imagecreatefromjpeg($imgsrc);
		$image = imagecreatetruecolor($imgWidth, $imgHeight);   //创建一个彩色的底图
		imagecopyresampled($image, $imgsrc, 0, 0, 0, 0,$imgWidth,$imgHeight,$arr[0], $arr[1]);
		imagejpeg($image,$savepath);        				    //保存jpg格式图片
		imagedestroy($image);
	}
    /**
	 * 发送预览
     *  http请求方式:?POST
     *  accessToken  微信的token    touser 公众号的openid      mpnews  图文消息的类型（media_id 素材上传到微信端返回的media_id）     msgtype  群发的消息类型
     *  $material_id    素材id
     *  $AccessTag      素材标签（分组）
     *  $media_id       用于预览的图文消息的media_id
     *  $type        预览发的消息类型，图文消息为news
     */
	public static function sendPreview($materialId,$touser,$mediaId)
	{
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		//      开放平台 - 查数据库secret
		Session::switchCustomer(0);
//      实例化开发平台数据模型
		$customer_weixin_profile = D('customer_weixin_profile');
		Session::switchCustomer($customerId);
		$material = M('material');
		$media = $material->where("id=$materialId")->field('media_id,xml,name')->find();
		$media_id = $media['media_id'];
		if (!$media_id) {
			$arr = self::uploadXmlNewsToWeiXin($media['xml'],$mediaId);//解析素材的xml
			foreach ($arr as $key => $value) {
				if (empty($value['picUrl'])) {
					$msg['code'] = 5;
					$msg['msg'] = "请把封面填写完整才可以群发";
					$msg['data'] = '';
					Output::instance()->object($msg);
					return;
				}
				if (empty($value['content'])) {
					$msg['code'] = 6;
					$msg['msg'] = "正文为空，填写完整才可以群发";
					$msg['data'] = '';
					Output::instance()->object($msg);
					return;
				}
				if (empty($value['title'])) {
					$msg['code'] = 7;
					$msg['msg'] = "请把标题填写完整才可以群发";
					$msg['data'] = '';
					Output::instance()->object($msg);
					return;
				}
				$filepath = self::saveFile($value['picUrl'], 'image');   //下载图片资源
				$thumb_media_id = WeixinApi::newUploadmedia('image', $filepath['path'],$mediaId);    //根据图片地址上传到微信公众号
				$tmp_media_id = json_decode(json_encode($thumb_media_id), true);    //将返回的数据转换成数组
				@unlink($filepath['path']);//删除图片
				$articles['articles'][] = array(
					'title' => $value['title'],
					'thumb_media_id' => $tmp_media_id['media_id'],
					'author' => $value['author'],
					'digest' => urlencode( $value['description']),
					'content_source_url' => $value['content_source_url'],
					'content' => $value['content'],
					'show_cover_pic' => '0'
				);
			}
			//将图文上传到微信公众号
			$data = WeixinApi::newUploadMaterial($articles,$mediaId);

			//判断是否上传成功
			if (!isset($data['media_id'])) {
				$msg['code'] = 2;
				$msg['msg'] = "图文上传失败";
				$msg['data'] = '';
				Output::instance()->object($msg);
				return;
			}
			$media_id = $data['media_id'];
		}
		$msgtype = 'mpnews';
		$result = WeixinApi::sendPreview($touser, $media_id, $msgtype,$mediaId);
		if ($result['errcode'] == 0) {
			$nick_name=$customer_weixin_profile->where("mediaId=$mediaId")->getField('nick_name',true);
			R('Log/add',array('material','145','微信素材库','发送预览','',$nick_name[0].'发送'.$media['name'].'给'.$touser.'用户预览'));
			$msg['code'] = 5;
			$msg['msg'] = "发送成功";
			$msg['data'] = '';
			Output::instance()->object($msg);
		} else {
			$msg['code'] = 4;
			$msg['msg'] = "发送失败";
			$msg['data'] = '';
			Output::instance()->object($msg);
		}
	}
	/**
	 * 所有的自媒体账号
	 * @param string $type  自媒体账号类型（微信、头条）
	 * @param string $search  搜索自媒体账号名称
	 * @param int $limit 查询条数
	 */
    public function getMedia($type,$search='',$limit=10,$reference=''){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		$userId = Session::$user["id"];
		if($type == 'weixin'){//获取所有的微信公众号
			$where['b.cid']=array('eq',$customerId);
			$where['type']=array('eq',1);
			$where['a.userId']=array('eq',$userId);
			$where['b.deleted']=array('eq',0);
			if(!empty($search)){
				$where['nick_name']= array("like","%".trim($search)."%");

			}
			Session::switchCustomer(0);
			$ind_media_edit = M('ind_media_edit as a');
			Session::switchCustomer($customerId);
            $result = $ind_media_edit
				->where($where)
				->join('wx_ind_media_info as b on a.mediaId=b.id')
				->join("left join wx_customer_weixin_profile as c on a.mediaId=c.mediaId")
				->join("wx_customer_user as d on b.reviewer=d.id ")
				->limit($limit)
				->field('c.mediaId,c.nick_name,c.user_name,fullName')
				->select();
			if($reference){
				return $result;
			}
            if($result){
                Output::instance()->object($result);
            }else{
                Output::instance()->resultCode(code_custom_error,"您没有任何自媒体账号可以发送群消息");
            }
        }else if($type=='toutiao'){//头条
			Session::switchCustomer(0);
			$where['b.cid']=array('eq',$customerId);
			$where['type']=array('eq',3);
			$where['a.userId']=array('eq',$userId);
			$where['b.deleted']=array('eq',0);

			if(!empty($search)){
				$where['b.screen_name']= array("like","%".trim($search)."%");

			}
			$ind_media_edit = M('ind_media_edit as a');
			Session::switchCustomer($customerId);
			$result = $ind_media_edit
				->where($where)
				->join('wx_ind_media_info as b on a.mediaId=b.id')
				->join("left join wx_customer_toutiao_profile as c on a.mediaId=c.mediaId")
				->join("wx_customer_user as d on b.reviewer=d.id ")
				->limit($limit)
				->field('c.mediaId,c.screen_name,fullName')
				->select();
			if($result){
				Output::instance()->object($result);
			}else{
				Output::instance()->resultCode(code_custom_error,"您没有任何自媒体账号可以发送群消息");
			}
		}
    }
	/**
	 * 获取某自媒体账号这的访问类型、账号分组标签等信息
	 * @param string $type  自媒体账号类型（微信、头条）
	 * @param int $mediaId  自媒体账号id
	 * @param string $userType  群发用户的标识
	 * @param string $search  搜索自媒体账号账号分组、访问类型名称
	 * @param int $limit 查询条数
	 */
	public function getMediaGroup($type,$mediaId,$userType='',$search='',$limit=10){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		if($type=='weixin'){//调取微信的分组、标签/用户访问类型具体信息
			if($userType=='group'){
				$user_weixin_group = M('user_weixin_group');
				if(!empty($search)){
					$where['group_name']= array("like","%".trim($search)."%");
				}
				$where['mediaId']=array('eq',$mediaId);
				$result = $user_weixin_group->where($where)->field('group_id,group_name,count')->select();
			}else{
				$access_tag = M('access_tag');
				if(!empty($search)){
					$where['tagName'] = array("like","%".trim($search)."%");
				}
				$where['mediaId']=array('eq',$mediaId);
				$result = $access_tag->where($where)->field('tagName,id')->select();
			}
			if(!empty($result)){
				Output::instance()->object($result);
			}else{
				Output::instance()->resultCode(code_custom_error,"该自媒体账号没有任何分组");
			}
		}else if($type=='toutiao'){//头条号的分类频道信息
			Session::switchCustomer(0);
			$toutiao_artice_tag=M('toutiao_article_tag');
			Session::switchCustomer($customerId);
			$result=$toutiao_artice_tag->select();
			if(!empty($result)){
				Output::instance()->object($result);
			}else{
				Output::instance()->resultCode(code_sql_error);
			}
		}

	}
	/**
	 * 群发列表
	 * @param $type      群发列表的类型
	 * @param int    $start
	 * @param int    $limit
	 */
	public function massList($type,$materialId,$start=0,$limit=10){
		//判断前台传过来的类型
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		if($type=='news'){
			$where['a.cid']=array('eq',$customerId);
			$where['a.type']=array('eq','news');
			$where['a.materialId']=array('eq',$materialId);
			Session::switchCustomer($customerId);
			$module_mass_havesend=M('module_mass_havesend as a');
			Session::switchCustomer($customerId);
			$result=$module_mass_havesend
				->where($where)
				->join("left join wx_customer_weixin_profile as b on a.mediaId=b.mediaId")
				->join("wx_".$customerId."_mass_review as d on a.id=d.massid")
				->limit($start,$limit)
				->order("id desc")
				->field('a.id,a.createTime,a.type,b.nick_name,a.status as Qstatus,d.status as Sstatus')
				->select();
			$count=$module_mass_havesend
				->where($where)
				->join("left join wx_customer_weixin_profile as b on a.mediaId=b.mediaId")
				->join("wx_".$customerId."_mass_review as d on a.id=d.massid")
				->count();
			if(empty($result)){
				Output::instance()->resultCode(code_custom_error,"没有任何群发");
			}else{
				Output::instance()->objArray($result,$count);
			}
		}elseif($type=='miContent'){
			$where['a.type']=array('eq','miContent');
			$where['a.cid']=array('eq',$customerId);
			$where['a.materialId']=array('eq',$materialId);
			Session::switchCustomer($customerId);
			$module_mass_havesend=M('module_mass_havesend as a');
			Session::switchCustomer($customerId);
			$result=$module_mass_havesend
				->where($where)
				->join("wx_customer_toutiao_profile as b on a.mediaId=b.mediaId")
				->join("wx_".$customerId."_mass_review as d on a.id=d.massid" )
				->limit($start,$limit)
				->order("id desc")
				->field("a.id,a.createTime,d.status as Sstatus,screen_name,a.status as Qstatus")
				->select();
			$count=$module_mass_havesend
				->where($where)
				->join("wx_customer_toutiao_profile as b on a.mediaId=b.mediaId")
				->join("wx_".$customerId."_mass_review as d on a.id=d.massid" )
				->count();
			if(empty($result)){
				Output::instance()->resultCode(code_custom_error,"没有任何群发");
			}else{
				Output::instance()->objArray($result,$count);
			}
		}



	}
	/**
	 * 新建群发
	 * @param $mediaId      自媒体账号id
	 * @param $userType     要群发的用户类型 （all：全部用户   group那个用户组的用户  access用户的访问类型）
	 * @param $labels       标签id  （组id 或 标签id  $userType 为all时传空）
	 * @param $materialId   素材id或文id
	 * @param $materialType 素材类型  群发类型（news:图文；content:文章）
	 * @param $sendType     发送时间（1为立即/2为定时）
	 * @param $sendTime     发送时间（立即为 当前时间/定时为 群发的时间）
	 * @param $send_ignore_reprint  /是否强制转载0否, 1是
	 */
    public function massAdd($mediaId,$userType,$labels='',$materialId,$materialType,$sendType,$sendTime='',$original=0,$toUserName='',$send_ignore_reprint=0)
	{
		//判断前台传过来的类型
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		//判断用户是否是编辑身份
		if (!Session::isEdit()){
			$return['code'] = 1;
			$return['msg'] = '您无此权限,请联系运营管理员';
			$return['data'] = '';
			Output::instance()->object($return);
			return $return;
		}

		$cid = Session::$user["customerId"];
		$fullName = Session::$user["fullName"];
		Session::switchCustomer(0);
//      实例化开发平台数据模型
		$customer_weixin_profile = D('customer_weixin_profile');
		Session::switchCustomer($cid);


        $data['mediaId'] = $mediaId;
        $data['cid'] = $cid;
        $data['original'] = $original;
        $data['type'] = $materialType;
        $data['massType'] = $userType;
        $data['labels'] = $labels;
        $data['materialId'] = $materialId;
        $data['openids'] = 0;
        $data['sendtime'] = ($sendType == 1) ? date("Y-m-d H:i:s") : $sendTime;
        $data['createTime'] = date("Y-m-d H:i:s");
        $data['sendType'] = $sendType;
        $data['status'] = 0;
        $data['toUserName'] = $toUserName;
        $module_mass_havesend = M('module_mass_havesend');
        $nick_name=$customer_weixin_profile->where("mediaId=$mediaId")->getField('nick_name',true);


		//添加群发
        $massId = $module_mass_havesend->add($data);

//		R('Log/add',array('material','145','微信素材库',op_add,$module_mass_havesend->getLastSql(),'群发人：'.$fullName.'群发账号:'.$nick_name[0].'群发时间'.$sendTime));
//		群发账号：魔镜俏佳人，群发时间：XXX”；对于修改用户的分组，描述为“设置用户XXX分组为XXX”

		if ($massId) {
				$customerId = Session::$user["customerId"];
				Session::switchCustomer(0);
				$ind_media_info = M('ind_media_info');
				Session::switchCustomer($customerId);
				//查询该自媒体账号是否需要审核

				$result = $ind_media_info->where("id=$mediaId")->field('reviewer,ifReview')->find();
				if ($result['ifReview'] == 0) {//为0则不需要审核
					//群发
					$msg = self::mass($massId, $materialId, $mediaId,$send_ignore_reprint);
					Output::instance()->object($msg);
					return;

				} else {
					//把群发的信息提交到审核表
					if ($materialType == 'miContent') {
						$contentId = $materialId;
						$msg = R('MiContent/submitContentMassReview', array($contentId, $mediaId, $result['reviewer'], $massId));
						Output::instance()->object($msg);
						return;
					} else if ($materialType == 'news') {
						$msg = self::submitMaterialMassReview($materialId, $mediaId, $result['reviewer'], $massId);
//						Output::instance()->object($msg);
						return $msg;
					}
				}
			} else {
				Output::instance()->resultCode(code_custom_error, "新建群发失败");
			}
	}
	/**
	 * 群发
	 * @param $massId  群发id
	 * @param $materialId 要群发的素材ID
	 * @param $materialId 是否强制转载
	 * @return array
	 */
	public function mass($massId,$materialId,$mediaId,$send_ignore_reprint=0){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer($customerId);
		$module_mass_havesend=M('module_mass_havesend');
		//查看此次群发的具体信息
		$massMsg=$module_mass_havesend->where("id=$massId")->find();
		if(empty($massMsg)){
			$resultBack = array(
				'code'=>-1,
				'msg'=>'群发信息不存在',
				'data'=>'',
			);
			return $resultBack;
		}
		//此时群发的状态为（1：正在发送）
		$status['status']=1;
		$module_mass_havesend->where("id=$massId")->save($status);
		if($massMsg['type']=='news'){
			$data['materialId']=$materialId;
			$data['massId']=$massId;
			$data['labels']=$massMsg['labels'];
			$data['type']=$massMsg['type'];
			$data['mediaId']=$mediaId;
			$data['send_ignore_reprint']=$send_ignore_reprint;
			$param=json_encode($data);
			//调取定时任务进行群发   name  任务的名称  material那个模块进行的任务   interfaceName执行的类 （通过sendType方法先把参数进行转换成数组，再进行发送）    param参数   sendtime执行的时间
			R('TaskQueue/addTaskQueue', array($name='pushWeiXinNews', $module='material',$interfaceName='MaterialAction/sendType',$param,$massMsg['sendtime']));
			return;
		}else{
			$data['mediaId']=$massMsg['mediaId'];
			$data['miContent']=$massMsg['materialId'];
			$data['article_tag']=$massMsg['labels'];
			$data['type']=$massMsg['type'];
			$data['massId']=$massId;
			$data['send_ignore_reprint']=$send_ignore_reprint;
			$param=json_encode($data);
			R('TaskQueue/addTaskQueue', array($name='pushToutiaoContent', $module='miContent',$interfaceName='MaterialAction/sendType',$param,$massMsg['sendtime']));
			return;
		}
	}
	/**
	 * 定时任务参数解析成数组
	 * $task   执行的任务数据
	 * */
	public function sendType($task){
		$data=json_decode($task['param'],true);
		$massId=$data['massId'];
		$module_mass_havesend=M('module_mass_havesend');
		$mass_review=M('mass_review');
		$review=$mass_review->where("massId=$massId")->field('updateTime')->find();
		$mass=$module_mass_havesend->where("id	=$massId")->field('updateTime,status')->find();
		//判断群发前素材是否改动
		if($review['updateTime'] < $mass['updateTime'] || $mass['status']==4){
			$data['status']=3;
			$result=$module_mass_havesend->where("id=$massId")->save($data);
			if($result){
				return true;
			}
		}
		if($data['type']=='news'){
			$msg=self::pushWeiXinNews($data['materialId'],$data['labels'],$data['massId'],$data['mediaId'],'1',$data['send_ignore_reprint']);
			if($msg['code']==0){
				$backupsId=self::materialBackups($data['materialId']);
				$save['backupsId']=$backupsId;
				$module_mass_havesend->where("id=$massId")->save($save);
				Output::instance()->object($msg);
				return true;
			}
		}else if($data['type']=='miContent'){
			$msg=R('MiContent/pushToutiaoContent', array($data['mediaId'],$data['miContent'],$data['article_tag']));
			$save['status']=3;
			if($msg['code']==0){
				$save['status']=2;
				R('MiContent/miContentBackups', array($data['miContent']));
			}
			$save['returntime']= date("Y-m-d H:i:s");
			$save['errcode']=$msg['code'];
			$save['errmsg']=$msg['msg'];
			$module_mass_havesend->where("id=$massId")->save($save);
			return true;
		}
	}
	/**
	 * 执行群发接口
	 * $materialId   群发的素材id
	 * $openids   要群发的用户openid
	 * $massId   群发数据id
	 * $sendType   群发类型
	 * */
	public function pushWeiXinNews($materialId,$labels,$massId,$mediaId,$sendType=''){
		Session::switchCustomer(0);

		/*jie新增,留言保存使用*/
		$customer_weixin_profile=M('customer_weixin_profile');

		$ind_media_info=M('ind_media_info');
		$cid=$ind_media_info->where("id=$mediaId")->getField('cid',true);
		Session::switchCustomer($cid[0]);
		//实例化开发平台数据模型
		$material=M('material');
		$module_mass_havesend=M('module_mass_havesend');
		$materialMsg=$material->where("id=$materialId")->find();
		if(empty($materialMsg)){
			$resultBack = array(
				'code'=>-1,
				'msg'=>'群发的素材不存在',
				'data'=>'',
			);
			return $resultBack;
		}

		$data=self::uploadXmlNewsToWeiXin($materialMsg['xml'],$mediaId);    //解析素材的xml

		$newCount = count($data);
		$articles = [];

		foreach($data as $key=>$value){
			$filepath = self::saveFile($value['picUrl'],'image');   //下载图片资源
			/*$thumb_media_id=WeixinApi::newUploadmedia('image',$filepath['path'],$mediaId);	//根据图片地址上传到微信公众号
			$tmp_media_id=json_decode(json_encode($thumb_media_id),true); 	//将返回的数据转换成数组
			$articles['articles'][] = array(
				'title' => $value['title'],
				'thumb_media_id' => $tmp_media_id['media_id'],
				'author' => $value['author'],
				'digest' => $value['digest'],
//				'content_source_url' => file_get_contents($value['content']),
				'content_source_url' => $value['content_source_url'],
				'content' => $value['content'],
				'show_cover_pic' => '0'
			);*/


			/*jie新增如果使用评论, 需要上传永久素材, 此处也需要获取永久素材mediaId*/
			$filepath['filename'] = $filepath['path'];
			$thumb_media_id=WeixinApi::add_material('image',$filepath,$mediaId);	//根据图片地址上传到微信公众号
			$tmp_media_id=json_decode($thumb_media_id,true); 	//将返回的数据转换成数组
			Log::write('jie-----------0000'.print_r($tmp_media_id, true));
			$articles['articles'][] = array(
				'title' => $value['title'],
				'thumb_media_id' => $tmp_media_id['media_id'],
				'author' => $value['author'],
				'digest' => $value['digest'],
//				'content_source_url' => file_get_contents($value['content']),
				'content_source_url' => $value['content_source_url'],
				'content' => $value['content'],
				'show_cover_pic' => '0',
				'need_open_comment'=>1,			//是否可以评论, 调add_news接口才可传
				'only_fans_can_comment'=>0		//是否只能粉丝评论
			);

		}

		//将图文上传到微信公众号
		//$tmp_news_media_id=WeixinApi::newUploadMaterial($articles,$mediaId);

		//将图文上传到微信公众号,调用add_news返回结果需要解析,使用永久素材
		$tmp_news_media_id = WeixinApi::add_news($articles,$mediaId);
		$tmp_news_media_id = json_decode($tmp_news_media_id, true);

		//判断是否上传成功
		if(!isset($tmp_news_media_id['media_id'])){
			$resultBack = array(
				'code'=>-1,
				'msg'=>'群发失败,请完事图文消息再进行群发',
				'data'=>'',
			);
			$data['status']=3;
			$data['errcode']=$tmp_news_media_id['errcode'];
			$data['errmsg']=wxErrCode($tmp_news_media_id['errcode']);
			$module_mass_havesend->where("id=$massId")->save($data);
			Log::write('jie-------1111'.print_r($tmp_news_media_id, true));
			return $resultBack;
		}
		$massType=$module_mass_havesend->where("id=$massId")->getField('massType');
		$massType=='all'?$massType=true:$massType=false;
		$msgtype='mpnews';
		//微信群发
		$massMsg=WeixinApi::sendAll($massType,$labels, $tmp_news_media_id['media_id'], $msgtype,$mediaId);
		//将返回的数据转换成数组
		$tmp_massMsg=json_decode($massMsg,true);
		//判断是否上传成功
		if(!isset($tmp_massMsg['msg_id'])){
			//修改群发的状态 （3为群发失败）
			$data['status']=3;
			$data['errcode']=$tmp_massMsg['errcode'];
			$data['errmsg']=wxErrCode($tmp_massMsg['errcode']);
			$module_mass_havesend->where("id=$massId")->save($data);
			$resultBack = array(
				'code'=>-2,
				'msg'=>'群发失败',
				'data'=>'',
			);
			return $resultBack;
		}else{
			//修改群发的状态 （2为群发成功）
			$data['status']=2;
			$data['errcode']=$tmp_massMsg['errcode'];
			$data['errmsg']=$tmp_massMsg['errmsg'];
			$data['msg_data_id']=$tmp_massMsg['msg_data_id'];
			$data['msg_id']=$tmp_massMsg['msg_id'];
			$module_mass_havesend->where("id=$massId")->save($data);

			/*jie新增保存消息id及图文索引表, 留言需要*/
			$user_name=$customer_weixin_profile->where(['mediaId'=>$mediaId])->getField('user_name');
			$sql = 'INSERT INTO `wx_news_index_comment`
(`cid`, `mediaId`,`wxappid`, `materialId`, `msg_data_id`, `msg_id`, `news_index`, `createTime`)
VALUES ';
			for($i=0; $i<$newCount; $i++){
				$sql .= "(" . $cid[0] . "," . $mediaId . ",'" . $user_name . "'," . $materialId . "," . $tmp_massMsg['msg_data_id'] . "," . $tmp_massMsg['msg_id'] . "," . $i . ",'" . date('Y-m-d H:i:s') . "'),";
			}
			$sql = trim($sql, ',') . ';';
			$result = M()->execute($sql);
			if(!$result){
				Log::write('jie群发图文第一次保存表失败:'.M()->getLastSql());
			}

			$resultBack = array(
				'code'=>0,
				'msg'=>'群发成功',
				'data'=>'',
			);
			return $resultBack;
		}
	}
	/**
	 * 群发素材备份
	 * $materialId   备份的素材id
	 * */
	public function materialBackups($materialId){
		$material=M('material');
		$msg=$material->where("id=$materialId")->select();
		if($msg){
			$msg[0]['backups']=$msg[0]['id'];//备份的类型被区分
			unset($msg[0]['id']);
			$materialId=$material->addAll($msg);//群发后留备份
		}
		return $materialId;
	}
	/**
	 * 群发详情
	 * @param $massId  群发id
	 */
	public function massDetails($massId){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$module_mass_havesend=M("module_mass_havesend");
		$arr=$module_mass_havesend->where("id=$massId")->find();
		if($arr){
			Output::instance()->objArray($arr);
		}else{
			Output::instance()->resultCode(code_sql_error);
		}

	}
	/**
	 * 群发删除
	 * @param $msg_id  删除群发id
	 * @param $article_idx  其中第几条
	 * @param $mediaId   自媒体id
	 */
	public function massDelete($msg_id,$article_idx=0,$mediaId){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$msg=WeixinApi::delmass($msg_id,$article_idx,$mediaId);
		if($msg['errcode']==0){
			$module_mass_havesend=M("module_mass_havesend");
			$newSingleId=$module_mass_havesend->where("msg_id=$msg_id")->field("newSingleId")->find();
			$data['newSingleId']=$newSingleId[0].','.$article_idx;
			$result=$module_mass_havesend->where("msg_id=$msg_id")->save($data);
			if($result){
				$return['code']=1;
				$return['msg']="删除成功";
				Output::instance()->objArray($return);
			}else{
				$return['code']=2;
				$return['msg']="删除失败";
				Output::instance()->objArray($return);
			}

		}else{
			$return['code']=3;
			$return['msg']="删除失败";
			Output::instance()->objArray($return);
		}
	}
    /**
     * 保存素材审核状态以及发送站内消息
     * @param int $materialId 素材ID
     * @param int $mediaId 媒体ID
     * @param int $reviewer 审核人ID
     * @param int $massId  群发ID
     * @return array $return 返回错误码和返回信息
     */
    public function submitMaterialMassReview($materialId,$mediaId,$reviewer,$massId)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        /**2.数据表模型*/
        $userId = Session::$user['id'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $user = M('customer_user');
        Session::switchCustomer($customerId);
        $review = M('mass_review');

        //判断用户是否是编辑身份
         if (!Session::isEdit()){
            $return['code'] = 1;
            $return['msg'] = '您无此权限,请联系运营管理员';
            $return['data'] = '';
            return $return;
        }

        /**3.发送站内消息,添加审核信息*/
        $userInfo = $user->field("fullName")->where("id=$reviewer")->find();
        $review->create();
        $review->materialId = $materialId;
        $review->mediaId = $mediaId;
        $review->userId = $userId;
        $review->reviewer = $reviewer;
        $review->createTime = date('Y-m-d H:i:s');
        $review->status = 1;
        $review->massId = $massId;
        $review->type= 1;
        $reviewId =$review->add();
        $review_sql = $review->getLastSql();
        R('Log/add',array('review','215','审核',op_add,$review_sql,'向'.$userInfo['fullName'].'提交图文审核'));
//        PlatMessageAction::pushMessage('图文群发审核', Session::$user["fullName"].'提交公众号群发前的图文审核, <a href="#/joymap/materialmanager/publish/audit">前往查看</a>', array($reviewer), $userId, 0, 'review', '审核', 1, 1, 0, 0,Session::$user["fullName"].'提交公众号群发前的图文审核, <a href="#/joymap/materialmanager/publish/audit">前往查看</a>');

		if ($reviewId){
            $return['code'] = 0;
            $return['msg'] = 'ok';
			$return['reviewId'] = $reviewId;
        }else{
            $return['code'] = 1;
            $return['msg'] = '审核信息添加失败';
        }
        return $return;

    }
     /**
     * 保存素材撤回状态
     * @param int $reviewId 审核ID
     * @return $return 返回错误码和返回信息
     */
    public function recallMaterialReview($reviewId)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.数据表模型*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $user = M('customer_user');
        $Model_MMCS             = M('media_mass_config_schedule');
        $Model_TaskQueue = M('task_queue');
        Session::switchCustomer($customerId);
        $material = M('material');
        $review = M('mass_review');
        $mass = M('module_mass_havesend');

        //判断用户是否是编辑身份
         if (!Session::isEdit()){
            $return['code'] = 1;
            $return['msg'] = '您无此权限,请联系运营管理员';
            $return['data'] = '';
            Output::instance()->object($return);
            return;
        }

        /**3.修改审核表的审核状态*/
        $materialInfo = $review->field('mediaId, materialId,reviewer,massId')->where("id=$reviewId")->find();
        $data_mass['status'] = 4;
        $data_mass['updateTime'] = date("Y-m-d H:i:s");
        $mass_result = $mass->where("id=".$materialInfo['massId'])->save($data_mass);

        // 撤回处理定时群发
        $mmcs = $Model_MMCS->where([
            'mediaId' => $materialInfo['mediaId'],
            'materialId' => $materialInfo['materialId'],
            'reviewType' => 2
        ])->find();
        if (!empty($mmcs)) {
            $Model_TaskQueue->where([
                'name' => 'pushWeiXinNews',
                'moduleName' => 'material',
                'execute_plan_time' => date('Y-m-d H:i:s', strtotime($mmcs['scheduleTime'] . ' ' . $mmcs['sendTime']))
            ])->save(['status' => 3]);
        }

        // 修改排期的审核状态字段reviewType = 0
        $Where_MMCS = [
            'mediaId' => $materialInfo['mediaId'],
            'materialId' => $materialInfo['materialId']
        ];
        $Res_MMCS = $Model_MMCS->where($Where_MMCS)->save(['reviewType' => 0]);
        \Log::write('撤回群发审核-修改排期审核状态 . $Res_MMCS = ' . json_encode($Res_MMCS) . '_sql = ' . $Model_MMCS->getLastSql());

        if ($mass_result !== false || !is_numeric($Res_MMCS)){
            $data_review['status'] = 4;
            $data_review['updateTime'] = date('Y-m-d H:i:s');
            $result_review = $review->where("id=$reviewId")->save($data_review);
            if ($result_review !== false){
                $data_material['lockTime'] = date("Y-m-d H:i:s");
                $result_material = $material->where("id=".$materialInfo['materialId'])->save($data_material);
                $reviewInfo = $user->field("fullName")->where("id=".$materialInfo['reviewer'])->find();
                $material_sql = $material->getLastSql();
                R('Log/add',array('review','215','审核',op_update,$material_sql,'将已送审到'.$reviewInfo['fullName'].'的图文撤回'));
                if ($result_material !== false){
                    $return['code'] = 0;
                    $return['msg'] = 'ok';
                    Output::instance()->object($return);
                }else{
                    $return['code'] = 1;
                    $return['msg'] = '图文锁定状态更改失败';
                    Output::instance()->object($return);
                }

            }else{
                $return['code'] = 1;
                $return['msg'] = '图文撤回状态修改失败，请重试';
                Output::instance()->object($return);
            }
        }else{
            $return['code'] = 1;
            $return['msg'] = '群发表图文撤回状态修改失败，请重试';
            Output::instance()->object($return);
        }



    }
     /**
     * 保存素材审核状态
     * @param int $result  审核结果（通过为1，不通过为0）
     * @param string $reviewOpinion 审核意见
     * @param int $reviewId  审核ID
     * @return array $return  返回错误码和返回信息
     */
    public function handleMaterialReview($result,$reviewOpinion='',$reviewId)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }


        /**2.数据表模型*/
        $userId = Session::$user['id'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $user = M('customer_user');
        Session::switchCustomer($customerId);
        $review = M('mass_review');
        $mass = M('module_mass_havesend');


        /**3.数据整理*/
        //取得审核基本信息
        $reviewInfo = $review->field('materialId,massId,status,userId,mediaId')->where("id=$reviewId")->find();
        $editId = $reviewInfo['userId'];
        $editInfo = $user->field('fullName')->where("id=$editId")->find();
        //根据用户审核意见处理不同逻辑
        if ($result){
        //判断用户审核是否被撤回
            if ($reviewInfo['status'] !== '4'){
                //更改图文素材审核状态
                $data_review['status'] = 2;
                $data_review['reviewOpinion'] = $reviewOpinion;
                $data_review['updateTime'] = date('Y-m-d H:i:s');
                $result_review = $review->where("id=$reviewId")->save($data_review);
                //判断审核表信息是否添加成功
                if ($result_review !== false){
                    $review_sql = $review->getLastSql();
                    R('Log/add',array('review','215','审核',op_update,$review_sql,'通过'.$editInfo['fullName'].'的图文审核'));
                    PlatMessageAction::pushMessage('图文过审','图文素材通过'.Session::$user['fullName'].'审核, <a href="#/joymap/materialmanager/publish/articles">前往查看</a>',array($reviewInfo['userId']),$userId,0,'review','审核',1, 1);
                    R('Material/mass',array($reviewInfo['massId'],$reviewInfo['materialId'],$reviewInfo['mediaId']));
                    $return['code'] = 0;
                    $return['msg'] = '图文素材经过审核';
                    Output::instance()->object($return);
                }else{
                    $return['code'] = 1;
                    $return['msg'] = '素材审核状态更改为通过失败,请重试';
                    Output::instance()->object($return);
                }
            }else{
                $return['code'] = 1;
                $return['msg'] = '该素材用户已经撤回';
                Output::instance()->object($return);
            }
        }else{
            //判断用户是否已经撤回该素材
            if ($reviewInfo['status'] !== '4'){
                //更改图文素材审核状态
                $data['status'] = 3;
                $data['reviewOpinion'] = $reviewOpinion;
                $data['updateTime'] = date('Y-m-d H:i:s');
                $result = $review->where("id=$reviewId")->save($data);
                if ($result !== false){
                    //发送站内消息通知审核状态
                    $review_sql = $review->getLastSql();
                    R('Log/add',array('review','215','审核',op_update,$review_sql,'驳回'.$editInfo['fullName'].'的图文审核'));
					$sendtime = $mass->where(['id' => $reviewInfo['massId']])->getField('sendtime');
                    PlatMessageAction::pushMessage('图文未过审','您的发送时间为'. $sendtime .'的图文素材未经过'.Session::$user['fullName'].'审核,审核意见为:'.$reviewOpinion . ', <a href="#/joymap/materialmanager/publish/articles">前往查看</a>',array($reviewInfo['userId']),$userId,0,'review','审核',1, 1);
                    //判断站内信息是否发送成功
                     $return['code'] = 0;
                     $return['msg'] = '该图文素材未经过审核，请重新提交审核';
                     Output::instance()->object($return);

                }else{
                    $return['code'] = 1;
                    $return['msg'] = '素材审核状态更改为未通过失败,请重试';
                    Output::instance()->object($return);
                }
            }else{
                $return['code'] = 1;
                $return['msg'] = '该图文素材用户已经撤回';
                Output::instance()->object($return);
            }
        }
    }
    /**
     * 得到各种审核状态的所有图文
     * @param int $status 默认0所有，1未审核的图文、2审核通过的图文、3审核未通过的图文
     * @param string $search 需要查询的标题
     * @param int $role 需要查询的角色1：审核人2：编辑,默认为1
     * @return array $return  返回错误码和返回信息
     */
    public function reviewMaterialList($status=0,$search='',$role=1, $start = 0, $limit = 10)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /** 2. 数据表模型 */
        $userId     = Session::$user['id'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $media = M('ind_media_info');
        Session::switchCustomer($customerId);
        $review = M('mass_review');

        $where['reviewer'] = $userId;
        $where['deleted'] = array("eq", 0);
        //$where['status'] = array("NEQ",4);
        $reviewer = $media->field('id')->where($where)->select();


        if ($reviewer && Session::isEdit()){
            if ($role == 1){
                $arr = R('Material/getReviewInfo',array($status,$search,$role, $start, $limit));
                $return['code'] = 2;
                $return['msg'] = 1;  //1.审核人身份，2.编辑身份
                $return['data'] = $arr;
                Output::instance()->object($return);
                return;
            }else if ($role == 2){
                $arr = R('Material/getReviewInfo',array($status,$search,$role, $start, $limit));
                $return['code'] = 2;
                $return['msg'] = 2;  //1.审核人身份，2.编辑身份
                $return['data'] = $arr;
                Output::instance()->object($return);
                return;
            }
        }
        if ($reviewer){
            $arr = R('Material/getReviewInfo',array($status,$search,1, $start, $limit));
            $return['code'] = 0;
            $return['msg'] = 1;  //1.审核人身份，2.编辑身份
            $return['data'] = $arr;
            Output::instance()->object($return);
        }else if (Session::isEdit()){
            $arr = R('Material/getReviewInfo',array($status,$search,2, $start, $limit));
            $return['code'] = 0;
            $return['msg'] = 2;   //1.审核人身份，2.编辑身份
            $return['data'] = $arr;
            Output::instance()->object($return);
        }else{
            $return['code'] = 1;
            $return['msg'] = '您无此权限,请联系运营管理员';
            $return['data'] = '';
            Output::instance()->object($return);
        }
    }
    /**
     * 得到具体图文信息
     * @param int $status 默认0所有，1未审核的图文、2审核通过的图文、3审核未通过的图文
     * @param string $search 需要查询的标题
     * @param int $role 需要查询的角色1：审核人2：编辑
     */
    public function getReviewInfo($status=0,$search='',$role, $start = 0, $limit = 10)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /** 2. 数据表模型 */
        $userId     = Session::$user['id'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        Session::switchCustomer($customerId);
        $review = M('mass_review');
        if ($role == 1){
            if ($status == 0){
                $where['reviewer'] = $userId;
                $where['type'] = 1;             //获取审核相关状态的所有图文  type：1.公众号，2：头条号
            }else{
                $where['reviewer'] = $userId;
                $where['status'] = $status;
                $where['type'] = 1;
            }
        }else if ($role == 2){
            //获取提交审核的所有图文  type：1.公众号，2.头条号
            if ($status == 0){
                $where['userId'] = $userId;
                $where['type'] = 1;            //获取审核相关状态的所有图文  type：1.公众号，2：头条号
            }else{
                $where['userId'] = $userId;
                $where['status'] = $status;
                $where['type'] = 1;
            }
        }

        $reviewInfo = $review->field('id,mediaId,massId,materialId')->where($where)->select();
        $reviewInfo = !empty($reviewInfo) ? $reviewInfo : [];
        for ($i = 0; $i < count($reviewInfo); $i++) {
            $reviewId[] = $reviewInfo[$i]['id'];
        }
        if(!empty($search)) {
            $where_select['mat.name|weixin.nick_name']= array("like","%".trim($search)."%");
        }
        if (!empty($reviewId)) {
            $where_select['re.id'] = array("IN", $reviewId);
        } else {
            $where_select['re.id'] = 0; // re.id = 0 的比如为空 20171116_bugid_1439
        }
        $where_select['re.status']=array("NEQ",4);
        $where_select['mat.deleted']=array("NEQ",1);
        $arr = $review->alias('re')
            ->join("LEFT JOIN  wx_".$customerId."_material as mat ON re.materialId = mat.id")
            ->join("LEFT JOIN  wx_customer_weixin_profile as weixin ON re.mediaId = weixin.mediaId")
            ->join("LEFT JOIN  wx_".$customerId."_module_mass_havesend as mass ON re.massId =mass.id ")
            ->join('wx_customer_user cu ON cu.id = re.userId')
            ->where($where_select)
            ->field("
                mat.*,mat.id as materialId,
                weixin.nick_name,weixin.head_img,weixin.service_type_info, weixin.mediaId,
                mass.sendtime,mass.sendType,
                re.id,re.massId,re.type,re.reviewOpinion,re.status,
                cu.fullName")
            ->order('re.createTime desc')
            ->limit($start, $limit)
            ->select();
        $total = $review->alias('re')
            ->join("LEFT JOIN  wx_".$customerId."_material as mat ON re.materialId = mat.id")
            ->join("LEFT JOIN  wx_customer_weixin_profile as weixin ON re.mediaId = weixin.mediaId")
            ->join("LEFT JOIN  wx_".$customerId."_module_mass_havesend as mass ON re.massId =mass.id ")
            ->join('wx_customer_user cu ON cu.id = re.userId')
            ->where($where_select)
            ->field('re.id')
            ->order('re.createTime desc')
            ->count();

        $review_sql = $review->getLastSql();
//        R('Log/add',array('material','145','微信素材库',op_find,$review_sql,'查看审核相关的所有图文'));
        $data = [
            'total' => $total,
            'data' => $arr
        ];
        return !empty($data) ? $data : ['total' => 0, 'data' => []];
    }
    /**
     * 获得图文素材的菜单
     *
     * @param $materialId  获得图文信息需要图文id, 所以这里url需要拼上
     */
    public function getMenuById($materialId)
    {

        // 菜单配置数组
        $data = [
            'group'     => '图文素材',
            'children'  => [
                [
                    'name'  => '编辑',
                    'url'   => '#/joymap/materialmanager/material/'.$materialId.'/news',
                ],
                [
                    'name'  => '群发',
                    'url'   => '#/joymap/materialmanager/material/'.$materialId.'/wxMass',
                ]
            ]

        ];

        $index = 1;
        $arr_child = [];
        foreach ($data['children'] as $child_k => $child_v) {
            // 这个菜单是_胡英俊_给出的菜单树demo结构
            $m = [
                'id'        => $index,
                'name'      => $child_v['name'],
                'level'     => 1,
                'parent'    => 0,
                'path'      => "$index",
                'icon'      => '',
                'url'       => $child_v['url'],
                'isMenu'    => true,
                'children'  => []
            ];
            array_push($arr_child, $m);
            $index++;
        }

        $menu = [
            'id'        => 0,
            'group'     => $data['group'],
            'children'  => $arr_child
        ];


        Output::instance()->object(['data' => [$menu]]);
    }
    /**
     * 删除商城缓存数据,对商城数据新加的缓存, 需要在这添加
     * @param $mid /商城id
     * @param $cId /cid
     */
    protected function cacheDel($mid, $cId){
        $redis = new RedisAPI();
        $redis->del('cId'.$cId.'mallId'.$mid);
        $redis->del('cid'.$cId.'mallid'.$mid.'groupId');
        $redis->del('cid'.$cId.'mallid'.$mid.'mallInfo');
        $redis->del('cid'.$cId.'mallid'.$mid.'mallHue');
    }
}
